<template>
  <div class="container">
    <div class="header" @click="$router.back(-1)">
      <i class="el-icon-arrow-left c-font-b"></i>
      <span>{{ foodId ? "菜品编辑" : "菜品新增" }}</span>
    </div>
    <!--    表单区域-->
    <div class="form">
      <el-form
        ref="formRef"
        :rules="formRules"
        :model="form"
        label-width="80px"
        label-position="right"
      >
        <el-form-item label="菜品图片" prop="image">
          <el-upload
            action="/api/storages"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            accept=".jpeg,.png,.jpg,.bmp,.gif"
            :before-upload="checkFileType"
            :file-list="fileList"
            :headers="header"
            name="multipartFile"
            thumbnail-mode
          >
            <i class="el-icon-plus"></i>
            <template #tip>
              <div class="el-upload__tip">
                <i class="el-icon-warning-outline"></i>
                <span class="c-m-l-5 c-font-12" style="color: #999999"
                  >图片支持JPG，Jpeg，Png，请上传10M以内的图片</span
                >
              </div>
            </template>
          </el-upload>
          <el-dialog v-model="imgDialogVisible">
            <el-image width="100%" height="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item
          label="菜品编号"
          prop="number"
          v-show="foodId ? true : false"
        >
          <el-input
            v-model="form.number"
            placeholder="请输入菜品编号"
            style="width: 200px"
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item label="菜品名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入菜品名称"
            style="width: 200px"
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item label="菜品归类" prop="type">
          <el-select
            v-model="form.type"
            class="m-2"
            placeholder="请选择菜品类型"
            size="small"
            style="width: 200px"
          >
            <el-option
              v-for="item in foodClassification"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属食堂" prop="region">
          <el-select
            style="width: 200px"
            size="small"
            v-model="form.region"
            placeholder="请选择食堂"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in canteenData"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="试吃时间">
          <el-date-picker
            v-model="form.tryTime"
            type="datetime"
            placeholder="请选择试吃时间"
            format="YYYY/MM/DD hh:mm:ss"
            size="small"
            style="width: 200px"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="试吃定价">
          <el-input
            v-model="form.tryPrice"
            size="small"
            style="width: 200px"
            placeholder="请输入价格"
          ></el-input>
          元
        </el-form-item>
        <el-form-item label="试吃图片" prop="tryImage">
          <el-upload
            action="/api/storages"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="tryHandleRemove"
            :on-success="tryHandleSuccess"
            accept=".jpeg,.png,.jpg,.bmp,.gif"
            :before-upload="checkFileType"
            :file-list="tryFileList"
            :headers="header"
            name="multipartFile"
            thumbnail-mode
          >
            <i class="el-icon-plus"></i>
            <template #tip>
              <div class="el-upload__tip">
                <i class="el-icon-warning-outline"></i>
                <span class="c-m-l-5 c-font-12" style="color: #999999"
                  >图片支持JPG，Jpeg，Png，请上传10M以内的图片</span
                >
              </div>
            </template>
          </el-upload>
          <el-dialog v-model="imgDialogVisible">
            <el-image width="100%" height="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="菜品详情" prop="details">
          <QuillEditor
            v-model:content="contentText"
            contentType="html"
            ref="quillHtml"
          />
          <i class="el-icon-warning-outline"></i>
          <span class="c-m-l-5 c-font-12" style="color: #999999"
            >文本内容最多控制在60-4000个字符以内，插入图片每张不超过500kb</span
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="getFoodData"
            >保存</el-button
          >
          <TsButton
            v-show="foodId"
            label="提交"
            type="success"
            size="small"
            @click="submitFoodAudit"
            perms="food:submit:put"
          ></TsButton>
          <el-button size="small" @click="$router.back(-1)">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { onMounted, reactive, ref } from "vue";
import {
  addFood,
  foodAudit,
  foodType,
  getCanteenList,
  getFood,
  updateFood,
} from "../../../api/canteen/dishes-managerApi";
import { ElMessage } from "element-plus";
import { QuillEditor } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import Cookies from "js-cookie";
import { useRoute, useRouter } from "vue-router";
import { checkNum } from "../../../utils";
export default {
  components: {
    QuillEditor,
  },
  name: "DishesEdit",
  setup() {
    const imgDialogVisible = ref(false);
    const dialogImageUrl = ref("");
    const contentText = ref("");
    const route = useRoute();
    const router = useRouter();
    //表单数据
    const form = reactive({});
    //表单标识
    const formRef = ref(null);
    //食堂数据
    const canteenData = ref([]);
    // 试吃图片列表
    const tryFileList = ref([]);
    // 菜品归类
    const foodClassification = ref([]);
    //获取食堂列表数据
    function getCanteenData() {
      getCanteenList().then((res) => {
        canteenData.value = res.data;
      });
    }
    //添加菜品数据
    function getFoodData() {
      if (foodId.value) {
        updateFood(foodId.value, {
          canteenId: form.region,
          details: contentText.value,
          name: form.name,
          number: form.number,
          images: fileList.value.map((item) => item.url).join(","),
          id: foodId.value,
          putawayStatus: form.putawayStatus,
          type: form.type,
          tryPrice: form.tryPrice,
          tryTime: form.tryTime,
          tryImages: tryFileList.value.map((item) => item.url).join(","),
        }).then(() => {
          ElMessage({
            message: "更新成功",
            type: "success",
          });
          formRef.value.resetFields();
          router.back(-1);
        });
      } else {
        addFood({
          canteenId: form.region,
          details: contentText.value,
          name: form.name,
          number: form.number,
          images: fileList.value.map((item) => item.url).join(","),
          putawayStatus: form.putawayStatus ? form.putawayStatus : false,
          type: form.type,
          tryPrice: form.tryPrice,
          tryTime: form.tryTime,
          tryImages: tryFileList.value.map((item) => item.url).join(","),
        }).then(() => {
          ElMessage({
            message: "添加成功",
            type: "success",
          });
          formRef.value.resetFields();
          router.back(-1);
        });
      }
    }
    //上传图片列表
    const fileList = ref([]);
    const header = reactive({ Authorization: Cookies.get("token") });
    //缩略图预览
    function handlePictureCardPreview(file) {
      imgDialogVisible.value = true;
      dialogImageUrl.value = file.url;
    }
    // 试吃图片缩略图预览
    //移除图片
    function handleRemove(file) {
      const i = fileList.value.findIndex((x) => x.url === file.url);
      fileList.value.splice(i, 1);
    }
    // 移除试吃图片
    function tryHandleRemove(file) {
      const tyrIndex = tryFileList.value.findIndex((i) => i.url === file.url);
      tryFileList.value.splice(tyrIndex, 1);
    }
    //图片上传成功时的回调
    function handleSuccess(file) {
      fileList.value.push({ url: file.data.url });
    }
    // 试吃图片上传成功时的回调
    function tryHandleSuccess(file) {
      tryFileList.value.push({ url: file.data.url });
    }
    //菜品ID
    const foodId = ref("");
    function getFoodDetail() {
      if (foodId.value) {
        getFood(foodId.value).then((res) => {
          form.number = res.data.number;
          form.name = res.data.name;
          form.region = res.data.canteenId;
          form.type = res.data.type;
          form.image = res.data.images;
          (form.tryPrice = res.data.tryPrice),
            (form.tryTime = res.data.tryTime),
            quillHtml.value.setHTML(res.data.details);
          const images = res.data.images.split(",");
          images.map((item) => {
            fileList.value.push({ url: item });
          });
          if (res.data.tryImages !== "" && res.data.tryImages !== null) {
            const tryImg = res.data.tryImages.split(",");
            tryImg.map((item) => {
              tryFileList.value.push({ url: item });
            });
          }
        });
      }
    }
    const quillHtml = ref(null);
    onMounted(() => {
      getCanteenData();
      foodId.value = route.query.id;
      // 获取菜品详情
      getFoodDetail();
      getFoodType();
    });
    const formRules = ref({
      number: [{ validator: checkNum, trigger: "blur" }],
    });

    function checkFileType(file) {
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf("."));
      // jpeg,.png,.jpg,.bmp,.gif
      if (
        fileType === ".jpg" ||
        fileType === ".png" ||
        fileType === ".jpeg" ||
        fileType === ".bmp" ||
        fileType === ".gif"
      ) {
        // 不处理
      } else {
        ElMessage.error(
          "不是,jpeg,.png,.jpg,.bmp,.gif文件,请上传正确的图片类型"
        );
        return false;
      }
    }
    //提交菜品审核
    function submitFoodAudit() {
      foodAudit([foodId.value])
        .then(() => {
          ElMessage.success("提交成功");
          router.back(-1);
        })
        .catch(() => {});
    }
    //获取菜品类型
    function getFoodType() {
      foodType().then((res) => {
        foodClassification.value = res.data;
      });
    }
    return {
      foodId,
      checkFileType,
      formRules,
      quillHtml,
      form,
      formRef,
      canteenData,
      getFoodData,
      handlePictureCardPreview,
      handleRemove,
      handleSuccess,
      fileList,
      header,
      contentText,
      dialogImageUrl,
      imgDialogVisible,
      submitFoodAudit,
      tryFileList,
      tryHandleRemove,
      tryHandleSuccess,
      foodClassification,
    };
  },
};
</script>
<style scoped lang="scss">
.el-form-item {
  margin-bottom: 10px;
}
.container {
  .header {
    padding-bottom: 20px;
    margin-bottom: 20px;
    border-bottom: 1px solid #edeff3;
  }
}
/deep/.ql-container.ql-snow {
  height: 200px;
  overflow-y: auto;
}
</style>
